import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../global/Global.dart';
import '../utils/rsa/rsa_utils.dart';
import '../viewmodel/LoginViewModel.dart';
import '../base/view.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  GlobalKey _key = GlobalKey<FormState>();
  var _username = new TextEditingController();
  var _password = new TextEditingController();

  // FocusNode _u = FocusNode();
  // FocusNode _p = FocusNode();

  onSubmit() {
    // 校验
    if((_key.currentState as FormState).validate()) {
      print('校验通过');
      context.read<LoginViewModel>().login(username: _username.text, password: _password.text);
      // Navigator.of(context).popAndPushNamed('/menu');
    }
    print(_username.text);
  }

  onRegister() {
    print('register');
    Navigator.of(context).pushNamed('/register');
  }

  @override
  void dispose() {
    super.dispose();
    _username.dispose();  // 注销 避免内存泄露
    _password.dispose();  // 注销 避免内存泄露
    // _u.dispose();  // 注销 避免内存泄露
    // _p.dispose();  // 注销 避免内存泄露
  }

  @override
  void initState() {
    super.initState();
    loadData();
  }


  void loadData() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    String? token = await sp.getString("token");
    print(token);
    if (token != null) {
      Global().getInstance().dio.options.headers["token"] = token;
      context.read<LoginViewModel>().tokenLogin(token);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: getAppbar('登陆'),
      body: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.all(20.0.r),
          child: Column(
            children: [
              // Image.asset('images/logo.jpg', width: double.infinity,),
              Image.network(
                'https://img2.baidu.com/it/u=2470716442,3652076975&fm=26&fmt=auto&gp=0.jpg',
                fit: BoxFit.fill,
              ),
              SizedBox(
                height: 10.h,
              ),
              // WeForm()
              Form(
                  key: _key,
                  // autovalidate: true, // 自动校验
                  autovalidateMode: AutovalidateMode.onUserInteraction,
                  child: (Column(
                    children: [
                      TextFormField(
                        decoration: InputDecoration(
                          prefixIcon: Icon(Icons.person),
                          labelText: '账号',
                          // hintText: "请输入账号"
                          // border: OutlineInputBorder(gapPadding: .1, borderRadius: BorderRadius.all(Radius.circular(10.0)))
                        ),
                        onChanged: (v) {
                          // print(v);
                        },
                        controller: _username,
                        textInputAction: TextInputAction.next, // 键盘确定键样式 下一个
                        validator: (v) {
                          if(v.toString().length == 0) {
                            return '请输入账号';
                          }
                        },
                        // autofocus: true,  //自动获取焦点
                        // focusNode: _u,
                        // onFieldSubmitted: (v) {
                        // //  回车监听
                        // },
                      ),
                      SizedBox(height: 20.h,),
                      TextFormField(
                        obscureText: true,
                        decoration: InputDecoration(
                          prefixIcon: Icon(Icons.lock),
                            labelText: '密码',
                            // border: OutlineInputBorder(),
                        ),
                        onChanged: (v) {
                          // print(v);
                        },
                        controller: _password,
                        // textInputAction: TextInputAction.next, // 键盘确定键样式
                        validator: (v) {
                          if(v.toString().length == 0) {
                            return '请输入密码';
                          }
                        },
                        onFieldSubmitted: (v) {
                          this.onSubmit();
                        },
                        // focusNode: _p,
                      ),
                      SizedBox(height: 8.h,),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          InkWell(
                            child: Text('找回密码', style: TextStyle(
                              color: Theme.of(context).primaryColor
                            ),),
                          )
                        ],
                      ),
                      SizedBox(height: 20.h,),
                      Container(
                        child: ElevatedButton(
                            onPressed: onSubmit,
                            child: Text('登陆'),
                        ),
                        width: double.infinity,
                      ),
                      SizedBox(height: 10.h,),
                      Container(
                        child: ElevatedButton(onPressed: onRegister, child: Text('注册')),
                        width: double.infinity,
                      )

                    ],
                  )))
            ],
          ),
        ),
      )

    );
  }
}


